function MyPromise(excutor) {
  this.PromiseState = 'pending' // MyPromise对象的状态
  this.PromiseResult = undefined // MyPromise对象的值
  this.callbacks = []
  let self = this

  function resolve_(data) {
    // 改变Mypromise的状态为fulfilled
    if (self.PromiseState !== 'pending') return
    self.PromiseState = 'fulfilled'
    self.PromiseResult = data

    // 执行then中的异步回调函数
    self.callbacks.forEach(callback => {
      callback.Resolved()
    })
  }

  function reject_(data) {
    if (self.PromiseState !== 'pending') return
    self.PromiseState = 'rejected'
    self.PromiseResult = data

    // 执行then中的第二个回调函数
    self.callbacks.forEach(callback => {
      callback.Rejected()
    })
  }

  try {
    excutor(resolve_, reject_)
  } catch (e) {
    reject_(e)
  }
}

MyPromise.prototype.then = function(onResolved, onRejected) {
  let self = this
  return new MyPromise((resolve, reject) => {
    // 实现then的链式调用，当有错误的时候包装为Promise错误对象

    function callback(type) {
      try {
        let thenReturn = type(self.PromiseResult)
        if (thenReturn instanceof MyPromise) {
          thenReturn.then(value => {
            console.log(1);
            resolve(value)
          }, reason => {
            reject(reason)
          })
        } else {
          resolve(thenReturn)
        }
      } catch (e) {
        // 出现错误返回Promise包装的对象
        reject(e)
      }
    }

    if (this.PromiseState === 'fulfilled') {
      callback(onResolved)
    } else if (this.PromiseState === 'rejected') {
      callback(onRejected)
    } else if (this.PromiseState === 'pending') {
      self.callbacks.push({
        Resolved() {
          callback(onResolved)
        },
        Rejected() {
          callback(onRejected)
        }
      })
    }
  })

}

let m = new MyPromise((resolve, reject) => {
  setTimeout(function() {
    reject('reject')
  }, 1000)
})

m.then(value => {
  console.log(value);
  return new MyPromise((resolve, reject) => {
    setTimeout(function() {
      resolve('resolve')
    }, 1000)
  })
}, (reason) => {
  console.log(reason);
}).then(value => {
  console.log(value);
}, reason => {
  console.log(reason);
})